<template>
    <div class="code-rule-container">
        <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
            <el-tab-pane label="模板管理" name="mb"></el-tab-pane>
        </el-tabs>

        <div class="table-container">
            <div style="margin-bottom: 10px;">
                <el-input v-model="searchName" placeholder="按模板名称查询" style="width: 200px; margin-right: 10px"></el-input>
                <el-select v-model="creatorSearch" filterable placeholder="选择创建人" style="width: 150px; margin: 0 5px">
                    <el-option
                        v-for="item in userOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
                <el-button icon="el-icon-search" circle @click="handleSearch"></el-button>
                <el-button type="warning" plain @click="handleReset" style="margin-left: 10px">重置/刷新</el-button>
                <el-button type="success" plain @click="handleAdd">新增模板</el-button>
            </div>

            <el-table :data="templates" style="width: 100%" :default-sort="{prop: 'id',order: 'descending'}" row-key="id" border stripe @expand-change="handleExpandChange">
                <!-- 展开行图标列 -->
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-table :data="expandedData[props.row.id] || []" style="width: 100%" v-loading="expandedLoading[props.row.id]" element-loading-text="加载中..." stripe>
                            <el-table-column prop="" label=" " width="100"></el-table-column>
                            <el-table-column prop="step" label="步骤顺序号" width="100"></el-table-column>
                            <el-table-column prop="stepName" label="步骤名称" width="120"></el-table-column>
                            <el-table-column label="步骤类型" width="120">
                              <template slot-scope="scope">
                                <span v-if="scope.row.stepType === 1">步骤</span>
                                <span v-else-if="scope.row.stepType === 2">审核</span>
                                <span v-else>-</span>
                              </template>
                            </el-table-column>
                            <el-table-column prop="handlerName" label="负责人" width="120"></el-table-column>
                            <el-table-column prop="description" label="备注描述"></el-table-column>
                        </el-table>
                        <div v-if="!expandedLoading[props.row.id] && (!expandedData[props.row.id] || expandedData[props.row.id].length === 0)" style="text-align: center; padding: 20px; color: #909399;">
                            暂无节点数据
                        </div>
                    </template>
                </el-table-column>

                <!-- 外层表格列 -->
                <!-- <el-table-column prop="id" label="ID" sortable width="80"></el-table-column> -->
                <el-table-column prop="templateName" label="模板名称" sortable width="120"></el-table-column>
                <el-table-column prop="username" label="创建人" sortable width="100"></el-table-column>
                <el-table-column prop="creatTime" label="创建时间" sortable width="140"></el-table-column>
                <el-table-column prop="modifierName" label="修改人" sortable width="100"></el-table-column>
                <el-table-column prop="updateTime" label="修改时间" sortable width="140"></el-table-column>
                <el-table-column prop="remark" label="备注"></el-table-column>

                <el-table-column label="操作" width="100" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" circle plain @click="handleEdit(scope.row)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" circle plain @click="handleDelete(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div style="margin: 10px 0;text-align: center; position: sticky; bottom: 0; background: white; z-index: 1;">
            <el-pagination @current-change="handleCurrentChange" :current-page="pageNum" :page-size="pageSize" layout="total,prev,pager,next" :total="total"></el-pagination>
        </div>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="90%">
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="模板名称" prop="templateName">
                            <el-input v-model="formData.templateName" placeholder="请输入模板名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-button @click="addChild" type="primary" plain size="small" icon="el-icon-plus" style="margin-bottom: 10px;">新增步骤</el-button>
                
                <el-table :data="formData.children || []" border max-height="400" stripe>
                    <el-table-column label="步骤序号" prop="step" width="100px">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.step" placeholder="请输入" size="small"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="步骤名称" prop="stepName" width="180px">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.stepName" placeholder="请输入" size="small" @input="handleStepNameInput(scope.row)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="步骤类型" prop="stepType" width="180px">
                        <template slot-scope="scope">
                            <!-- 使用自定义样式的单选框组，避免aria-hidden警告 -->
                            <div class="custom-radio-group">
                                <label class="custom-radio">
                                    <input type="radio" v-model="scope.row.stepType" :value="1" class="custom-radio-input">
                                    <span class="custom-radio-label">步骤</span>
                                </label>
                                <label class="custom-radio">
                                    <input type="radio" v-model="scope.row.stepType" :value="2" class="custom-radio-input">
                                    <span class="custom-radio-label">审核</span>
                                </label>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="负责人" prop="handler" width="180px">
                        <template slot-scope="scope">
                            <!-- <el-input v-model="scope.row.handler" placeholder="请输入" size="small"></el-input> -->
                             <el-select v-model="scope.row.handler" filterable placeholder="选择负责人" style="width: 150px; margin: 0 5px">
                                <el-option
                                    v-for="item in userOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="description" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.description" placeholder="请输入" size="small"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="80" align="center">
                        <template slot-scope="scope">
                            <el-button @click.native.prevent="removeChild(scope.$index)" type="text" size="small" icon="el-icon-delete">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
/**
 * 流程节点模板管理组件
 * 用于管理流程节点模板的创建、编辑、删除和查看
 */
export default {
    name: 'ProcessNode',
    data() {
        return {
            userOptions: [],
            userOptionsLoading: false,
            activeTab: 'mb',
            templates: [],
            dialogVisible: false,
            dialogTitle: '新增模板',
            formData: {
                id: null,
                templateName: '',
                remark: '',
                children: [] // 添加子节点数据
            },
            formRules: {
                templateName: [
                    {
                        required: true,
                        message: '请输入模板名称',
                        trigger: 'blur',
                    },
                ],
            },
            pageNum: 1,
            pageSize: 9,
            total: 0,
            loading: true,
            searchName: '',
            creatorSearch: '',

            // 展开行相关数据
            expandedData: {}, // 存储展开行的数据
            expandedLoading: {}, // 存储展开行的加载状态
        }
    },
    created() {
        this.fetchDictionaries()
    },
    mounted() {
        this.initUsersOptions()
    },
    methods: {
        /**
         * 初始化用户选项
         */
        initUsersOptions() {
            this.userOptionsLoading = true
            // 从后端接口获取用户数据
            this.$request.get('user/getSelect')
                .then(res => {
                    if (res.code === '200') {
                        this.userOptions = res.data;
                    } else {
                        this.$message.error(res.msg || '获取用户数据失败')
                        // fallback to mock data if API fails
                        this.userOptions = [
                            { value: 1, label: '张三' },
                            { value: 2, label: '李四' },
                            { value: 3, label: '王五' },
                            { value: 46, label: '赵科俭' },
                        ]
                    }
                })
                .catch(() => {
                    this.$message.error('网络错误，获取用户数据失败')
                    // fallback to mock data if API fails
                    this.userOptions = [
                        { value: 1, label: '张三' },
                        { value: 2, label: '李四' },
                        { value: 3, label: '王五' },
                        { value: 46, label: '赵科俭' },
                    ]
                })
                .finally(() => {
                    this.userOptionsLoading = false
                })
        },

        /**
         * 处理搜索
         */
        handleSearch() {
            this.pageNum = 1
            this.fetchDictionaries()
        },

        /**
         * 处理重置
         */
        handleReset() {
            this.searchName = ''
            this.creatorSearch = ''
            this.fetchDictionaries()
        },

        /**
         * 处理页码变化
         */
        handleCurrentChange(pageNum) {
            this.pageNum = pageNum
            this.fetchDictionaries()
        },

        /**
         * 处理标签切换
         */
        handleTabClick(tab) {
            this.activeTab = tab.name
            this.fetchDictionaries()
        },

        /**
         * 获取模板数据
         */
        fetchDictionaries() {
            this.loading = true
            // 调用后端接口获取模板数据
            this.$request({
                method: 'GET',
                url: 'processNode/findByPage',
                params: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    templateName: this.searchName,
                    creator: this.creatorSearch
                }
            }).then(res => {
                if (res.code === '200') {
                    const data = res.data
                    this.templates = data.records
                    this.total = data.total
                } else {
                    this.$message.error(res.msg || '获取模板数据失败')
                }
            }).catch(error => {
                this.$message.error('获取模板数据失败: ' + error.message)
            }).finally(() => {
                this.loading = false
            })
        },

        /**
         * 处理表格展开/收起
         */
        handleExpandChange(row, expanded) {
            if (expanded) {
                // 设置加载状态
                this.$set(this.expandedLoading, row.id, true);
                // 加载子节点数据
                this.loadChildDataForEdit(row.id, () => {
                    // 数据加载完成后的处理
                });
            } else {
                // 收起行时，清除该模板的加载状态
                this.$delete(this.expandedLoading, row.id);
            }
        },

        /**
         * 通用的获取节点数据方法
         */
        fetchNodeData(nodeId, callback = null) {
            this.expandedLoading[nodeId] = true;
            this.$request({
                url: 'processNode/getChildrenById',
                method: 'GET',
                params: { id: nodeId }
            }).then(res => {
                if (res.code === '200') {
                    const data = res.data || [];
                    this.$set(this.expandedData, nodeId, data);
                    if (callback) callback(data);
                } else {
                    this.$message.error('获取节点数据失败: ' + res.msg);
                    this.$set(this.expandedData, nodeId, []);
                    if (callback) callback([]);
                }
            }).catch(error => {
                this.$message.error('获取节点数据失败: ' + error.message);
                this.$set(this.expandedData, nodeId, []);
                if (callback) callback([]);
            }).finally(() => {
                this.expandedLoading[nodeId] = false;
            });
        },

        /**
         * 为编辑操作加载子节点数据
         */
        loadChildDataForEdit(templateId, callback) {
            // 如果已经加载过该模板的子节点数据，直接使用
            if (this.expandedData[templateId]) {
                // 确保加载状态已更新
                this.$set(this.expandedLoading, templateId, false);
                callback(this.expandedData[templateId]);
                return;
            }

            this.fetchNodeData(templateId, callback);
        },

        /**
         * 处理新增
         */
        handleAdd() {
            this.dialogTitle = '新增模板'
            this.formData = {
                id: null,
                templateName: '',
                remark: '',
                children: [] // 初始化空的子节点数组
            }
            // 重置表单验证
            if (this.$refs.formRef) {
                this.$refs.formRef.resetFields()
            }
            this.dialogVisible = true
        },

        /**
         * 处理编辑
         */
        handleEdit(row) {
            this.dialogTitle = '编辑模板'
            // 获取该模板的子节点数据
            this.loadChildDataForEdit(row.id, (childData) => {
                this.formData = {
                    id: row.id,
                    templateName: row.templateName,
                    remark: row.remark,
                    children: childData || [] // 将子节点数据赋值给formData
                }
                // 重置表单验证
                if (this.$refs.formRef) {
                    this.$refs.formRef.resetFields()
                }
                this.dialogVisible = true
            })
        },

        /**
         * 处理删除
         */
        handleDelete(id) {
            this.$confirm('确定要删除该模板吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 调用后端接口删除模板
                this.$request({
                    method: 'DELETE',
                    url: `processNode/template/${id}`
                }).then(res => {
                    if (res.code === '200') {
                        this.$message.success('删除成功')
                        // 重新获取数据
                        this.fetchDictionaries()
                        // 清除缓存的展开行数据
                        delete this.expandedData[id]
                    } else {
                        this.$message.error(res.msg || '删除失败')
                    }
                }).catch(error => {
                    this.$message.error('删除失败: ' + error.message)
                })
            }).catch(() => {
                // 用户取消删除
                this.$message.info('已取消删除')
            })
        },

        /**
         * 提交表单
         */
        submitForm() {
            // 先验证子项必填字段
            let isValid = true;
            let errorMsg = '';

            if (!this.formData.children || this.formData.children.length === 0) {
                isValid = false;
                errorMsg = '请添加至少一个步骤';
            } else {
                for (let i = 0; i < this.formData.children.length; i++) {
                    const child = this.formData.children[i];
                    // 步骤序号验证
                    if (!child.step) {
                        isValid = false;
                        errorMsg = `第${i + 1}个步骤的序号不能为空`;
                        break;
                    }
                    // 步骤名称验证
                    if (!child.stepName) {
                        isValid = false;
                        errorMsg = `第${i + 1}个步骤的名称不能为空`;
                        break;
                    }
                    // 负责人验证
                    if (!child.handler) {
                        isValid = false;
                        errorMsg = `第${i + 1}个步骤的负责人不能为空`;
                        break;
                    }
                }
            }

            if (!isValid) {
                this.$message.error(errorMsg);
                return;
            }

            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    // 表单验证通过
                    const isEdit = !!this.formData.id
                    const url = isEdit ? 'processNode/update' : 'processNode/save'
                    const method = isEdit ? 'PUT' : 'POST'

                    // 处理子节点数据，确保step字段存在并添加handlerName
                    const formDataWithChildren = {
                        ...this.formData,
                        children: this.formData.children.map(child => ({
                            ...child,
                            // 确保step是数字类型
                            step: Number(child.step) || 0,
                            // 尝试从不同字段获取handler名称，添加调试日志
                            handlerName: (() => {
                                // 如果handler是对象，尝试直接获取label
                                if (typeof child.handler === 'object' && child.handler !== null) {
                                    return child.handler.label || child.handler.name || child.handler.title || '';
                                }
                                // 如果handler是值类型，去userOptions中查找对应的label
                                if (this.userOptions && Array.isArray(this.userOptions)) {
                                    const foundOption = this.userOptions.find(option => option.value === child.handler);
                                    if (foundOption) {
                                        return foundOption.label;
                                    } else {
                                        console.warn('用户列表中找不到匹配项:', child.handler);
                                    }
                                }
                                return '';
                            })()
                        }))
                    }

                    this.$request({
                        method: method,
                        url: url,
                        data: formDataWithChildren
                    }).then(res => {
                        if (res.code === '200') {
                            this.$message.success(isEdit ? '更新成功' : '创建成功')
                            this.dialogVisible = false
                            // 重新获取数据
                            this.fetchDictionaries()
                            // 清除缓存的展开行数据（如果是编辑）
                            if (isEdit) {
                                delete this.expandedData[this.formData.id]
                                // 重新加载当前节点的数据
                                this.loadNodeData(this.formData.id)
                            } else {
                                // 如果是新增，刷新整个列表
                            }
                        } else {
                            this.$message.error(res.msg || (isEdit ? '更新失败' : '创建失败'))
                        }
                    }).catch(error => {
                        this.$message.error((isEdit ? '更新失败' : '创建失败') + ': ' + error.message)
                    })
                } else {
                    // 表单验证失败
                    return false;
                }
            })
        },

        /**
         * 新增子项
         */
        addChild() {
            if (!this.formData.children) {
                this.$set(this.formData, 'children', [])
            }
            
            // 计算新的step值，从1开始自动递增
            let newStep = 1;
            if (this.formData.children.length > 0) {
                // 找到当前最大的step值
                const maxStep = Math.max(...this.formData.children.map(item => Number(item.step) || 0));
                newStep = maxStep + 1;
            }
            
            this.formData.children.push({
                step: newStep.toString(),
                stepName: '',
                stepType: 1, // 默认步骤类型为'步骤'(值为1)
                handler: '',
                description: ''
            })
        },

        /**
         * 删除子项
         */
        removeChild(index) {
            if (this.formData.children && this.formData.children.length > 0) {
                this.formData.children.splice(index, 1);
                // 删除后重新排列step序号
                this.reorderSteps();
            }
        },

        // 重新排列子项的step序号
        reorderSteps() {
            if (this.formData.children && this.formData.children.length > 0) {
                this.formData.children.forEach((item, index) => {
                    item.step = (index + 1).toString();
                });
            }
        },

        /**
         * 加载指定节点的数据
         */
        loadNodeData(nodeId) {
            this.fetchNodeData(nodeId);
        },

        // 处理步骤名称输入，检测是否包含'审核'或'审批'二字
        handleStepNameInput(row) {
            if (row.stepName && (row.stepName.includes('审核') || row.stepName.includes('审批'))) {
                row.stepType = 2;
                row.handler = 46;
            } else if (row.stepType === 2) {
                // 如果移除了'审核'或'审批'二字且当前是审批类型，则改回步骤类型
                row.stepType = 1;
                row.handler = null;
            }
        }
    },
}
</script>

<style scoped>
.code-rule-container {
    padding: 10px 10px 60px;
}
.table-container {
    margin-top: 5px;
}

/* 展开行内容样式优化 */
.el-table__expanded-cell {
    padding: 10px 20px !important;
}

.el-table__expanded-cell .el-table {
    margin: 0;
}

/* 对话框样式优化 */
.el-dialog__body {
    padding: 20px;
}

.el-form-item {
    margin-bottom: 15px;
}
/* 自定义单选框样式，避免Element UI原生组件的aria-hidden警告问题 */
.custom-radio-group {
    display: flex;
    align-items: center;
}

.custom-radio {
    display: flex;
    align-items: center;
    margin-right: 15px;
    cursor: pointer;
}

.custom-radio-input {
    /* 隐藏原生radio样式 */
    position: absolute;
    opacity: 0;
    cursor: pointer;
}

.custom-radio-label {
    position: relative;
    padding-left: 22px;
    cursor: pointer;
}

/* 自定义radio样式 */
.custom-radio-label:before {
    content: "";
    position: absolute;
    left: 0;
    top: 2px;
    width: 14px;
    height: 14px;
    border: 1px solid #dcdfe6;
    border-radius: 50%;
    background-color: #fff;
    transition: border-color 0.3s;
}

/* 选中状态样式 */
.custom-radio-input:checked + .custom-radio-label:before {
    border-color: #409eff;
}

/* 选中状态的内部圆点 */
.custom-radio-input:checked + .custom-radio-label:after {
    content: "";
    position: absolute;
    left: 4px;
    top: 6px;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: #409eff;
}

/* 移除可能导致aria-hidden警告的样式 */
.el-radio__original {
    aria-hidden: false !important;
}

/* 确保表格内的输入元素在获得焦点时不被隐藏 */
.el-table__body-wrapper .custom-radio-input:focus + .custom-radio-label:before {
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

</style>
